package com.qmerak.action;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qmerak.common.ExcelUtil;
import com.qmerak.common.FromProgressModel;
import com.qmerak.common.ServletFileUploadExt;
import com.qmerak.common.StringUtil;
import com.qmerak.common.SystemUtil;
import com.qmerak.entity.MemberEntity;
import com.qmerak.service.IMemberService;

/**
 * app向导
 * 
 * @author hexin
 * 
 */
@Controller
@RequestMapping("/file")
public class FileUploadAction {

	private static final Logger LOG = LoggerFactory.getLogger(FileUploadAction.class);
	private static long MAX_UPLOAD_SIZE = 536870912;
	private static String UPLOAD_PATH = SystemUtil.getWebRootPath() + "\\upload";
	private static String UPLOAD_TMP_PATH = SystemUtil.getWebRootPath() + "\\upload\\temp";

	/**
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	public String upload(HttpServletRequest request) {
		LOG.info("upload  ---------:" + request.hashCode());
		File file = null;
		List<Map<String, Object>> listFile = new ArrayList<Map<String, Object>>();
		try {
			ServletFileUploadExt fileUpload = createFileUpload();
			List<FileItem> items = fileUpload.parseRequest(request);
			System.out.println(SystemUtil.getWebRootPath());
			Map<String, Object> loadFileMap = new HashMap<String, Object>();
			for (FileItem fileItem : items) {
				String fileName = null;
				InputStream inputStream = null;
				if (!fileItem.isFormField()) {
					fileName = fileItem.getName();
					if (StringUtil.isNotBlank(fileName)) {
						inputStream = fileItem.getInputStream();
						file = new File(UPLOAD_PATH, UUID.randomUUID().toString());
						LOG.info("create file >>>> " + file);
						FileOutputStream outputStream = new FileOutputStream(file);
						byte[] buf = new byte[1024];
						int length = 0;
						while ((length = inputStream.read(buf)) != -1) {
							outputStream.write(buf, 0, length);
							outputStream.flush();
						}
						outputStream.close();
					}
				} else {
					String tmpFieldName = fileItem.getFieldName();
					String value = fileItem.getString("UTF-8");
					loadFileMap.put(tmpFieldName, value);
					LOG.info("tmpFieldName >>>>> {} ,value >>> {}", tmpFieldName, value);
				}
			}
			listFile.add(loadFileMap);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return file.getPath();
	}

	/**
	 * 对apache commons 的fileupload进行建档封装
	 * 
	 * @return
	 */
	private ServletFileUploadExt createFileUpload() {
		final FromProgressModel progressModel = new FromProgressModel();
		DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
		fileItemFactory.setRepository(SystemUtil.createPath(UPLOAD_TMP_PATH));
		ServletFileUploadExt fileUpload = new ServletFileUploadExt(fileItemFactory, progressModel);
		fileUpload.setFileSizeMax(MAX_UPLOAD_SIZE);
		fileUpload.setProgressListener(new ProgressListener() {
			public void update(long bytesRead, long contentLength, int itemId) {
				long progress = Math.round(100.00 * bytesRead / contentLength);
				String tmpProgress = Long.toString(progress);
				Map<String, String> item = progressModel.getItemMap(itemId);
				if (item != null) {
					if (tmpProgress.equals(item.get("progress"))) {
						return;
					}
				}
				progressModel.updateProgress(itemId, tmpProgress);
			}
		});
		return fileUpload;
	}

	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping("uploadprogress")
	public String uploadprogress(@RequestParam("formId") String formId, @RequestParam("fieldName") String fieldName,
			HttpServletRequest request) {
		LOG.info("uploadprogress  formId >>" + formId + "  fieldName >> " + fieldName);
		String progress = "";
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		HttpSession session = request.getSession();
		Map<String, FromProgressModel> map = (Map<String, FromProgressModel>) session.getAttribute(ServletFileUploadExt.SESSION_FORM_MAP);
		FromProgressModel fromProgressModel = map.get(formId);
		if (fromProgressModel != null) {
			progress = fromProgressModel.getProgress(fieldName);
			if (StringUtil.isBlank(progress)) {
				progress = "0";
				LOG.error("fieldName >>" + fieldName + "   没有找到进度.. progress >> " + progress);
			} else {
				LOG.debug("fieldName >>" + fieldName + "   进度.. progress  >>" + progress);
			}
		}
		return progress;
	}

	@ResponseBody
	@RequestMapping("download")
	public void loadFile(@RequestParam("fileName") String fileName, HttpServletRequest request, HttpServletResponse response)
			throws UnsupportedEncodingException {
		LOG.info("loadFile  fileName  >>>  {}", fileName);
		String tFileName = URLDecoder.decode(fileName, "UTF-8");
		LOG.info("loadFile  tFileName  >>>  {}", tFileName);

		File file = new File(tFileName);
		if (file.exists()) {
			response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
			response.addHeader("Content-Length", "" + file.length());
			response.setContentType("application/octet-stream;charset=UTF-8");
			FileInputStream fs = null;
			FileChannel channel = null;
			OutputStream outputStream = null;
			try {
				fs = new FileInputStream(file);
				channel = fs.getChannel();
				ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
				while ((channel.read(byteBuffer)) > 0) {
				}
				byte data[] = byteBuffer.array();
				outputStream = new BufferedOutputStream(response.getOutputStream());
				outputStream.write(data);

			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					channel.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					fs.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			throw new RuntimeException("下载文件不存在!!!!");
		}
	}

	@Autowired
	private IMemberService memberService;

	@ResponseBody
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public void add(@RequestParam("filePath") String filePath) {
		try {
			File file = new File(filePath);
			FileInputStream fileInputStream = new FileInputStream(filePath);
			List<Map<String, Object>> datas = ExcelUtil.read(fileInputStream, 2);
			System.out.println(datas);
			for (Map<String, Object> map : datas) {
				MemberEntity memberEntity = new MemberEntity();
				memberEntity.setName(String.valueOf(map.get("0")));
				memberEntity.setIdNumber(String.valueOf(map.get("1")));
				memberService.add(memberEntity);
			}
			fileInputStream.close();
			file.delete();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
